package com.simpleframe.views.ui;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.tagext.BodyTagSupport;

public class IteratorTag extends BodyTagSupport {
	
	private static final long serialVersionUID = 1L;
	private Object value;
	private String var;
	
	public void setValue(Object value){
		this.value = value;
	}
	
	public void setVar(String var) {
		this.var = var;
	}
	
	public IteratorTag() {
		super();
	}
	
	Iterator it = null;
	
	public int doStartTag() {
		if(value!=null){
			if(value instanceof Collection ) {
				it = ((Collection)value).iterator();
			}else if(value instanceof Object[]){
				it = Arrays.asList((Object[])value).iterator();
			}else {
				throw new RuntimeException("标签内容只能够为 Collection、Object[] 类型数据，当前类型为："+value.getClass());
			}
		}
		
		if (it == null){
			return SKIP_BODY;
		}else
			return continueNext(it);
	}

	public int doAfterBody() {
		return continueNext(it);
	}

	public int doEndTag() {
		try {
			if (bodyContent != null && it != null)
				bodyContent.writeOut(bodyContent.getEnclosingWriter());
		} catch (Exception e) {
			System.out.println(e);
		}
		return EVAL_PAGE;
	}

	protected int continueNext(Iterator it) {
		if (it.hasNext()) {
			Object object = it.next();
			pageContext.setAttribute(var, object, pageContext.PAGE_SCOPE);
			return EVAL_BODY_TAG;
		} else
			return SKIP_BODY;
	}
}
